require "twitter"
require "twitter-text"

class Tweet < ActiveRecord::Base
  include Twitter::Autolink
    
  validates_presence_of :text, :tweet_created_at, :tweet_id, :user_name, :user_screen_name
  
  attr_accessible :text, :tweet_created_at, :tweet_id, :user_name, :user_screen_name, :user_profile_image_url

  default_scope :order => "tweet_created_at DESC"
  
  def text
    auto_link(self[:text]) 
  end

  def user_profile_image_url=(url)
    self[:user_profile_image_url] = url.sub("_normal", "_reasonably_small")
  end

  def self.find_by_tweet_id(tweet_id)
    if Tweet.exists?(:tweet_id => tweet_id.to_s)
      Tweet.where(:tweet_id => tweet_id.to_s).first
    else
      status = Twitter.status(tweet_id)
      tweet = Tweet.new
      tweet.text                    = status.text
      tweet.tweet_created_at        = status.created_at
      tweet.tweet_id                = status.id
      tweet.user_name               = status.user.name
      tweet.user_screen_name        = status.user.screen_name
      tweet.user_profile_image_url  = status.user.profile_image_url
      tweet.save!
      tweet
    end
  end
end